package com.zxl.manager.controller;

import com.zxl.manager.entity.User;
import com.zxl.manager.service.UserService;
import com.zxl.manager.utils.CryptUtil;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 逍遥的熊 on 2017/8/8.
 */
@Controller
@SessionAttributes("userInfo")
public class UserController {

    @Autowired
    private UserService userService;

    private Logger logger = Logger.getLogger(UserController.class);

    @RequestMapping("login")
    public ModelAndView login(String userid,String passwd,ModelMap model){
        ModelAndView mv = new ModelAndView();

        User user = userService.getUserByName(userid);
        if (StringUtils.isEmpty(user.getName()) || user.getName() == null){
            mv.getModel().put("err", "用户不存在");
            mv.setViewName("user/login");
        }else {
            String nPasswd = CryptUtil.MD5(passwd + user.getSalt());
            logger.debug("nPasswd:" + nPasswd);
            if (nPasswd.endsWith(user.getPassword())) {
                mv.setViewName("main");
                model.addAttribute("userInfo", user);
            } else {
                mv.getModel().put("err", "密码错误");
                mv.setViewName("user/login");
            }
        }
//
        return mv;
    }

    @RequestMapping("loginPage")
    public ModelAndView loginPage(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("user/login");
        return mv;
    }
}
